//
//  Foundation+Extension.swift
//  TodayNews
//
//  Created by monkey on 2020/3/8.
//  Copyright © 2020 itcast. All rights reserved.
//

import Foundation

extension Int
{
    var countString: String {
        if self < 10000 {  // 小于1万
            return "\(self)"
        } else if self % 10000 == 0 { // 整数万
            return String(format: "%d万", self / 10000)
        } else if self % 1000 == 0 { // 32000
            return String(format: "%.1f万", Double(self) / 10000.0)
        }else {
            return String(format: "%.2f万", Double(self) / 10000.0)
        }
    }
}

/// 日期格式化器
private let kDateFormatter:DateFormatter = DateFormatter()

extension Date
{
    // 结构体中 要是有类方法 要使用static修饰
    
    /// 将日期转换为格式化字符串
    ///
    /// - Parameter sinceNow: 与当前时间的差
    /// - Returns: String
    public static func convertToString(sinceNow:TimeInterval) -> String
    {
        let date = Date(timeIntervalSinceNow: sinceNow)
        kDateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        kDateFormatter.locale = Locale(identifier: "en")
        return kDateFormatter.string(from: date)
    }
        
    /// 返回当前日期的格式化字符串
    ///
    /// - Parameter format: 日期格式
    /// - Returns: String
    public func convertToString(format:String = "yyyy-MM-dd HH:mm:ss") -> String
    {
        kDateFormatter.dateFormat = format
        kDateFormatter.locale = Locale(identifier: "en")
        return kDateFormatter.string(from: self)
    }
    
    /// 返回创建时间
    /// 刚刚(一分钟内)
    /// X分钟前(一小时内)
    /// X小时前(当天)
    /// 昨天 HH:mm(昨天)
    /// MM-dd HH:mm(一年内)
    /// yyyy-MM-dd HH:mm(更早期)
    /// - Returns: String

    public static func convertToCreateString(sinceNow: TimeInterval) -> String
    {
        let createTimeDate = Date(timeIntervalSince1970: sinceNow)
        let currentCalendar = Calendar.current
        if currentCalendar.isDateInToday(createTimeDate) {
            // 今天
            let seconds = createTimeDate.timeIntervalSinceNow * -1
            if seconds < 60 {
                return "刚刚"
            } else if seconds < 3600 {
                return String(format: "%d", Int(seconds / 60)) + "分钟前"
            } else {
                return String(format: "%d", Int(seconds / 3600)) + "小时前"
            }
        } else if currentCalendar.isDateInYesterday(createTimeDate) {
            // 昨天
            return "昨天" + createTimeDate.convertToString(format: "HH:mm")
        } else {
            // 一年内或是超出一年
            let year = (currentCalendar.dateComponents(Set(arrayLiteral: Calendar.Component.year), from: createTimeDate, to: Date()).year ?? 0)
            let format = year < 1 ? "MM-dd HH:mm" : "yyyy-MM-dd HH:mm"
            return createTimeDate.convertToString(format: format)
        }
    }
}
